package tt.dz.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import tt.dz.dao.ext.charger.OmsChargerDao;
import tt.dz.dao.ext.system.OmsOperationSpListDao;
import tt.dz.entity.base.JsonCommon;
import tt.dz.entity.base.JsonForHardware;
import tt.dz.entity.base.JsonForHardwareData;
import tt.dz.entity.base.JsonForList;
import tt.dz.entity.charger.OmsCharger;
import tt.dz.entity.charger.OmsChargerRate;
import tt.dz.entity.system.OmsOperList;
import tt.dz.entity.system.OmsOperationSpList;
import tt.dz.mvc.controller.base.BaseAction;


@Component
public class StringUtil {

	// @Resource(name = "jdbcTemplateTool")
	// private JdbcTemplateTool jdbcTemplateTool;
	@Resource
	OmsChargerDao omsChargerDao ;//TODO, static field cannotbe injected, null pointer
	@Resource
	OmsOperationSpListDao omsOperationSpListDao;
	
	private static StringUtil su;
	/** 定义空对象,用户判断对象数据是否为空 */
    private static final Object NULL_OBJECT = null;

	@PostConstruct
	public void init() {

		su = this;
		su.omsChargerDao = this.omsChargerDao;
		su.omsOperationSpListDao = this.omsOperationSpListDao;
	}

//	public static String dzAppURL = "http://192.168.254.7/dz/index.php?m=app_server&c=return_api";

	public static String returnFalseJson() {
//		tt.dz.util.http.HttpUtils.getRequest(urlValue, paramMap)
		JsonForHardware json = new JsonForHardware();
		json.setCode("0");
		json.setMsg("false");
		String jsonString = JSON.toJSONString(json);
		return jsonString;
	}	
	
	public static boolean isNumeric(String str) {
		if(isBlank(str)){
			return false;
		}
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	public static String getSKeyLink(String keyLink) { // s_key_link
		// key_link: 0755300000000015
		// s_key_link:0000003055071500
		if (StringUtils.isNotBlank(keyLink) && keyLink.length() == 16) {
			String sKeyLink = keyLink.substring(10, 12) + keyLink.substring(8, 10) + keyLink.substring(6, 8)
					+ keyLink.substring(4, 6) + keyLink.substring(2, 4) + keyLink.substring(0, 2)
					+ keyLink.substring(14, 16) + keyLink.substring(12, 14);
			return sKeyLink;
		}
		return null;
	}

	// "00000000010" 到 "00000000011"
	public static String getNextCode(String code) {
		if (code.length() >= 16) {
			code = code.substring(5);
		}
		if (!isNumeric(code)) {
			return "00000000010";
		}
		int codeInt = Integer.valueOf(code);
		codeInt++;
		int kk = 11 - String.valueOf(codeInt).length();
		StringBuilder sb = new StringBuilder(String.valueOf(codeInt));
		for (int i = 0; i < kk; i++) {
			sb.insert(0, "0");
		}
		return sb.toString();
	}

	public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
		if (map == null)
			return null;

		Object obj = beanClass.newInstance();

		org.apache.commons.beanutils.BeanUtils.populate(obj, map);

		return obj;
	}

	public static Map<?, ?> objectToMap(Object obj) {
		if (obj == null)
			return null;

		return new org.apache.commons.beanutils.BeanMap(obj);
	}

	public static String[] getMessageHeader(String msg) {
		// &data=68001E0100000000010755300000000015A120151123120442000050242196850201000000000000000000000000000000000001020102
		/// 报文头
		// 启动字符68报文长度001E是否注册01响应码000000运营商0001充电设备地址0755300000000015帧类型A1流水号20151123120442
		// 报文体 报文头 25 报文体 30
		// String fac_login_name = data.substring(51, 58); //注册账号 00005024
		// String fac_password = data.substring(59, 67); //注册密码 21968502
		// String ev_fac_type1 = data.substring(18, 34); //设备一级类型 01
		// String ev_fac_type2 = data.substring(18, 34); //设备二级类型 00
		// String ev_sn = data.substring(18, 34); //设备SN 16位
		// String ev_gps = data.substring(18, 34); //GPS坐标 16位 00..00
		// String ev_soft_version1 = data.substring(18, 34); //版本号 0102
		if ((msg == null) || (msg.length() < 50)) {
			return null;
		}
		String[] header = new String[8];
		header[0] = msg.substring(0, 2);// 启动字符68 code_type
		header[1] = msg.substring(2, 6);// 报文长度001E
		header[2] = msg.substring(6, 8);// 0x00:未注册 0x01:已注册
		header[3] = msg.substring(8, 14);// 响应码000000
		header[4] = msg.substring(14, 18);// 运营商0001
		header[5] = msg.substring(18, 34);// 充电设备地址0755300000000015
											// char_login_record[登录记录表]中 设备地址
											// key_link
		header[6] = msg.substring(34, 36);// 帧类型A1 常常变
		header[7] = msg.substring(36, 50);// 流水号20151123120442
											// char_login_record[登录记录表]中 时间 time
		return header;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map<String,String> getParameterByMiddle(HttpServletRequest request) {
		Map map = new HashMap();
		map.put("ip", getRemoteHost(request));
		map.put("chargerId", request.getParameter("keylink"));
		map.put("port", request.getParameter("port"));//中间件服务器端口
		map.put("source_ip", request.getParameter("source_ip"));
		map.put("source_port", request.getParameter("source_port"));//桩使用的端口
		if(request.getParameter("protocol_type")==null){
			map.put("protocol_type", "1");//协议类型  1：EV3C；2：Protocol Translate；3 P2P 
		}else{
			map.put("protocol_type", request.getParameter("protocol_type"));//协议类型  1：EV3C；2：Protocol Translate；3 P2P 
		}
		map.put("protocol_version", request.getParameter("protocol_version"));//通讯协议版本号 0101 0102 0103
		if(request.getParameter("protocol_version")==null){
			map.put("protocol_version", "0103");//协议类型  1：EV3C；2：Protocol Translate；3 P2P 
		}else{
			map.put("protocol_version", request.getParameter("protocol_version"));//协议类型  1：EV3C；2：Protocol Translate；3 P2P 
		}
		String userCard = request.getParameter("userCard");
		String cardType ="";
		if(isNotBlank(userCard)){
			cardType = getCardType(userCard);
			map.put("userCard", userCard);
			map.put("cardType", cardType);
		}
		//以下是报文头
		String data = request.getParameter("data");
		if ((data == null) || (data.length() < 50)) {
			return null;
		}
		map.put("data", data);
		map.put("codeType", data.substring(0, 2));// 启动字符68 code_type
		map.put("msgBodylength",  data.substring(2, 6));// 报文长度001E
		map.put("isRegisted", data.substring(6, 8));// 0x00:未注册 0x01:已注册
		map.put("responseCode", data.substring(8, 14));// 响应码000000
		map.put("operId", data.substring(14, 18));// 运营商0001
		map.put("chargerId",  data.substring(18, 34));// 充电设备地址0755300000000015
		map.put("frameType",  data.substring(34, 36));// 帧类型A1 常常变
		map.put("serialNumber",  data.substring(36, 50));// 流水号20151123120442
		return map;
	}
	
	private static String getCardType(String userCard) {
		if(isBlank(userCard)||userCard.length()<5){
			return null;
		}
//		switch(userCard.substring(0, 5)){
//		case "18808":
//			return "08";
//		case "18806":
//			return null;
//		case "18805":
//			return null;
//		default:
//			return null;
//		}
		return userCard.substring(3, 5);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map<String,String> getParameterByOms(HttpServletRequest request) {
		//2.0 的 报文头String sendMsgBody,String frameCode,String chargerId,String chargerType,String portNo, String encryption
		HttpSession session = request.getSession();
		Map map = new HashMap();
		String chargerId = request.getParameter("chargerId");
		OmsCharger charger_query  = new OmsCharger();
		charger_query.setCharger_id(chargerId);
//				OmsCharger charger = findOneExample(charger_query, null, null);
//				OmsCharger charger = findCharger(charger_query);
		OmsCharger charger = su.omsChargerDao.findOneExample(charger_query, null, null);
		if(charger!=null && charger.getCharger_type()!=null && charger.getProtocol_type()!=null && charger.getProtocol_version()!=null){
			map.put("chargerType", String.valueOf(charger.getCharger_type()));
			map.put("protocol_type", String.valueOf(charger.getProtocol_type()));
			map.put("protocol_version", String.valueOf(charger.getProtocol_version()));
		} else {
			map.put("chargerType", "2");//直流
			map.put("protocol_type", "1"); //协议类型  1：EV3C；2：Protocol Translate；3 P2P 
			map.put("protocol_version", "0201"); //通讯协议版本号 0101 0102 0103
		}
//		map.put("protocol_type", protocol_type);
//		map.put("protocol_version", protocol_version);

		//预约 充电2.0下发报文
		map.put("bespeakStartSerialNumber", request.getParameter("bespeakStartSerialNumber"));
		map.put("chargeStartSerialNumber", request.getParameter("chargeStartSerialNumber"));
		
		map.put("login_oper_id", session.getAttribute("login_oper_id"));
		map.put("chargerId", request.getParameter("chargerId"));
		map.put("source_port", request.getParameter("source_port"));//桩使用的端口
		//可能的参数
		map.put("operId", request.getParameter("operId"));//运营商编号，电桩是0001
		map.put("userCard", request.getParameter("userCard"));
		map.put("portNo", request.getParameter("portNo"));
		map.put("bespeakMinute", request.getParameter("bespeakMinute"));//预约时长  单位：分   例 ：预约2小时30分钟     实际传输数据为：0x96 0x00
		map.put("communicationNo", request.getParameter("communicationNo"));//communication_no 运营商通讯编号,电桩为0001
		map.put("encryption", request.getParameter("encryption"));
		
		//设置服务器IP
		map.put("main_hardware_ip", request.getParameter("main_hardware_ip"));//主硬件服务器ip
		map.put("main_port", request.getParameter("main_port"));//主硬件服务器端口
		map.put("back_headware_ip", request.getParameter("back_headware_ip"));//备用硬件服务器ip
		map.put("back_port", request.getParameter("back_port"));//备用硬件服务器端口
		//是否需要重新注册	BIN码	1		0x00: 不需重新注册，使用已有设备地址直接在新服务器签到。0x01：需要重置“是否已注册”标记，切换到新服务器后重新注册获取设备地址。
		map.put("is_re_register", request.getParameter("is_re_register"));
		//固件更新下发
		map.put("software_version_after", request.getParameter("software_version_after"));
		map.put("download_ip", request.getParameter("download_ip"));
		map.put("download_port", request.getParameter("download_port"));
		map.put("software_identifier", request.getParameter("software_identifier"));
		map.put("download_time", request.getParameter("download_time"));
		map.put("retry_interval", request.getParameter("retry_interval"));
		map.put("retry_times", request.getParameter("retry_times"));
		//费率设置  下发
		map.put("rate1", request.getParameter("rate1"));
		map.put("rate2", request.getParameter("rate2"));
		map.put("rate3", request.getParameter("rate3"));
		map.put("rate4", request.getParameter("rate4"));
		map.put("fee_rate", request.getParameter("fee_rate"));
		map.put("time1", request.getParameter("time1"));
		map.put("time2", request.getParameter("time2"));
		map.put("time3", request.getParameter("time3"));

		map.put("schema_no", request.getParameter("schema_no"));

		//6.3.8电桩白名单卡号设置
		map.put("oper", request.getParameter("oper"));
		map.put("whitelist", request.getParameter("whitelist"));
		//6.3.9电桩参数查询/设置
		map.put("control_type", request.getParameter("control_type"));
		map.put("param_no", request.getParameter("param_no"));
		map.put("param", request.getParameter("param"));
		
		//以下是报文头
//				String data = request.getParameter("data");
//				if ((data == null) || (data.length() < 50)) {
//					return null;
//				}
//				map.put("data", data);
//				map.put("codeType", data.substring(0, 2));// 启动字符68 code_type
//				map.put("msgBodylength",  data.substring(2, 6));// 报文长度001E
//				map.put("isRegisted", data.substring(6, 8));// 0x00:未注册 0x01:已注册
//				map.put("responseCode", data.substring(8, 14));// 响应码000000
//				map.put("operId", data.substring(14, 18));// 运营商0001
//				map.put("chargerId",  data.substring(18, 34));// 充电设备地址0755300000000015
//				map.put("frameType",  data.substring(34, 36));// 帧类型A1 常常变
//				map.put("serialNumber",  data.substring(36, 50));// 流水号20151123120442
		return map;
	}
	
	// public static void callStates(){
	//
	// $this->BW_head['code_type'] = "71";
	// $this->sendBWtoDZ();
	// }

	public static String getRemoteHost(javax.servlet.http.HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
	}
	public static String ev3cMsgBodyBin(String ev3c_msgBody){
		String  length16 = Integer.toHexString(ev3c_msgBody.length() / 2);
		if(length16.length()==1){
			length16 = "0"+length16+"00";
		}else if(length16.length()==2){
			length16 =  length16+"00";
		}
		return length16;
	}
	// ip地址转16进制，去掉.
	public static String ip2HexStr(String ip) {
		String[] ips = ip.split("\\.");
		StringBuilder sb = new StringBuilder("");
		for (String tempip : ips) {
			// Integer.toHexString(Integer.valueOf(tempip));
			sb.append(String.valueOf(Integer.toHexString(Integer.valueOf(tempip))));
			// tempip
		}
		return sb.toString();
	}
	//ip 16进制转10进制 	0XD3  0X95  0XE4  0X65 转成  211.149.228.101
	public static String sixteen2ip(String ip16) {
		return Integer.valueOf(ip16.substring(0, 2), 16).toString()+"."+
		Integer.valueOf(ip16.substring(2, 4), 16).toString()+"."+
		Integer.valueOf(ip16.substring(4, 6), 16).toString()+"."+
		Integer.valueOf(ip16.substring(6, 8), 16).toString();
	}
	//时间14位的年月日时分秒 转化为16进制返回
	public static String sixteen2time14(String time) {
		if (StringUtils.isBlank(time)) {
			time = now14time();
		}
		//以下方法有问题
		return Integer.valueOf(time.substring(0, 4), 16).toString()+
		Integer.valueOf(time.substring(2, 4), 16).toString()+
		Integer.valueOf(time.substring(4, 6), 16).toString()+
		Integer.valueOf(time.substring(6, 8), 16).toString();
	}
	// 16进制转10进制
	public static String sixteen2tenStr(String str) {
		// Integer.toHexString(Integer.valueOf(str));
		// Integer.toHexString(200);
		return Integer.valueOf(str, 16).toString();
	}

	// 16进制转10进制
	public static int sixteen2tenInt(String str) {
		// Integer.toHexString(Integer.valueOf(str));
		// Integer.toHexString(200);
		return Integer.valueOf(str, 16);
	}

	// 根据数据系数原来是放大还是缩小过的16进制，还原成10进制的数据 param为100就是缩小100.
	public static int int16to10ByParam(String str, int param) {
		int strEnlarged = Integer.valueOf(str, 16);
		int resultInt;
		if (param != 1) {
			resultInt = strEnlarged / param;
			return resultInt;
		}
		return strEnlarged;
	}
	// 此方法丢弃  根据数据系数原来是放大还是缩小过的16进制，还原成10进制的数据 param为100就是缩小100.
	public static float float16to10ByParam(String str, int param) {
		int in = Integer.valueOf(str, 16);
		// float fl = Float.parseFloat(str);
		float fl = (float) in;
		float result = fl / param;
		return result;
	}

	//	放大100倍，低字节在前，高字节在后   放大100倍，低字节在前，高字节在后0x10 0x0e 0x00 0x00  表示充电金额为36元  3600的16进制是e10 3622的16进制是e26
	//	0x10 0x0e 0x00 0x00   转换成 36     0x26 0x0e 0x00 0x00   转换成 36.22   param 为100或者1
	public static float float16to10ByParamDesc(String str, int param)
	{
		//		str = "100e0000";  str = "260e0000";
		//		if(str.length()!=8){
		//			return  0;
		//		}
		StringBuilder sb = new StringBuilder("");
		for (int i = 0; i < str.length(); i = i + 2)
		{
			sb.append(str.substring(str.length() - i - 2, str.length() - i));
		}
		//		String k_str  = str.substring(6, 8)+str.substring(4, 6)+str.substring(2, 4)+str.substring(0, 2);
		long k_int = Long.parseLong(sb.toString(), 16);

		//		 float   f   =  34.232323;
		//		 BigDecimal   b  =   new BigDecimal(f);
		//		 float   f1   =  b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
		float f = k_int;
		float f1 = f / param;
		BigDecimal b = new BigDecimal(f1);
		float f2 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
		return f2;
		//		 float num=(float)(Math.round(f2*100)/100);
		//		 return  num;
		//		return  k_int/param;
	}
	
	public static String str16to10ByParamDesc(String str, int param){
//		str = "100e0000";  str = "260e0000";
//		if(str.length()!=8){
//			return  0;
//		}
		StringBuilder sb=new StringBuilder("");
		for(int i=0;i<str.length();i=i+2){
			sb.append(str.substring(str.length()-i-2, str.length()-i));
		}
//		String k_str  = str.substring(6, 8)+str.substring(4, 6)+str.substring(2, 4)+str.substring(0, 2);
		int k_int = Integer.parseInt(sb.toString(), 16);
		
//		 float   f   =  34.232323;  
//		 BigDecimal   b  =   new BigDecimal(f);  
//		 float   f1   =  b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue(); 
		 float   f   =  k_int;  
		 float   f1 =  f/param;
		 BigDecimal   b  =   new BigDecimal(f1);  
		 float   f2   =  b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue(); 
		 return  String.valueOf(f2);
//		return  k_int/param;
	}
	public static float Str2float(String str){
//		float a = 123.2334f; 
		float a = Float.valueOf(str);
		float b = (float)(Math.round(a*100))/100;
		return b;
	}
	
////	36.22元转换成0x26 0x0e 0x00 0x00，本方法是楼上方法的逆方法   param：放大倍数，可能是100 ，也可能是1；length:补齐位数：可能是8，也可能为4
//	public static String float10to16ByParamDesc(String str, int param,int length){
//		float f = Float.valueOf(str);
//		int k_int = (int)(f*param);
//		String k_Str_16 =Integer.toHexString(k_int);
//		if(k_Str_16.length()<length){
//			k_Str_16 = complement(k_Str_16,length);//00000e26
//		}
//		String result  = "";
//		if(length == 8){
//			result  = k_Str_16.substring(6, 8)+k_Str_16.substring(4, 6)+k_Str_16.substring(2, 4)+k_Str_16.substring(0, 2);
//		}else if(length == 4){
//			result  = k_Str_16.substring(2, 4)+k_Str_16.substring(0, 2);
//		}else if(length == 2){
//			result  = k_Str_16.substring(0, 2);
//		}
//		return  result;
//	}
	
//	36.22元转换成0x26 0x0e 0x00 0x00，本方法是楼上方法的逆方法   param：放大倍数，可能是100 ，也可能是1；length:补齐位数：可能是8，也可能为4
	public static String float10to16ByParamDesc(String str, int param,int length){
		BigDecimal b1 = new BigDecimal(str);   
		BigDecimal b2 = new BigDecimal(String.valueOf(param));   
		int k_int = b1.multiply(b2).intValue();
		String k_Str_16 =Integer.toHexString(k_int);
		if(k_Str_16.length()<length){
			k_Str_16 = complement(k_Str_16,length);//00000e26
		}
		String result  = "";
		int i = 0;
		for(;i<length;i =i+2){
			result = result +  k_Str_16.substring(length - i - 2, length - i);
		}
		return  result;
	}
	// 字符串（其实是数字）根据位数，在左边补位
	public static String complement(String codeStr, int length) {
		// String codeStr = String.valueOf(code);
		StringBuilder sb = new StringBuilder(codeStr);
		if (codeStr.length() >= length) {
			return String.valueOf(codeStr.substring(0, length));
		}
		int len = length - codeStr.length();
		for (int i = 0; i < len; i++) {
			sb.insert(0, "0");
		}
		return sb.toString();
	}
	/**
	 * 字符串转换成十六进制字符串
	 * 
	 * @param str
	 *            str 待转换的ASCII字符串
	 * @return String 每个Byte之间空格分隔，如: [61 6C 6B]
	 */
	public static String str2HexStr(String str) {

		char[] chars = "0123456789ABCDEF".toCharArray();
		StringBuilder sb = new StringBuilder("");
		byte[] bs = str.getBytes();
		int bit;

		for (int i = 0; i < bs.length; i++) {
			bit = (bs[i] & 0x0f0) >> 4;
			sb.append(chars[bit]);
			bit = bs[i] & 0x0f;
			sb.append(chars[bit]);
			sb.append(' ');
		}
		return sb.toString().trim();
	}

	// 返回当前时间的14位 年月日时分秒
	public static String now14time() {
		// 得到long类型当前时间
		long l = System.currentTimeMillis();
		// new日期对象
		Date date = new Date(l);
		// 转换提日期输出格式
		// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd
		// HH:mm:ss");
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		// System.out.println(dateFormat.format(date));
		return dateFormat.format(date);
	}
	// 返回当前时间的14位 年月日时分秒
	public static String dateTo14Str(Date date) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
		if(date == null){
			// 得到long类型当前时间
			long l = System.currentTimeMillis();
			// new日期对象
			Date date1 = new Date(l);
			// 转换提日期输出格式
			// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd
			// HH:mm:ss");
			// System.out.println(dateFormat.format(date));
			return dateFormat.format(date1);
		}else{
			return dateFormat.format(date);
		}

	}
	// 返回当前时间的14位 年月日时分秒
	public static String now12time() {
		// 得到long类型当前时间
		long l = System.currentTimeMillis();
		// new日期对象
		Date date = new Date(l);
		// 转换提日期输出格式
		// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd
		// HH:mm:ss");
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
		// System.out.println(dateFormat.format(date));
		return dateFormat.format(date);
	}
	// 返回某个时间的14位带冒号横杠的 年月日时分秒，不输入参数的话就以当前时间为准
	public static String time14format(String time) throws Exception {
		if (StringUtils.isBlank(time)) {
			// 得到long类型当前时间
			long l = System.currentTimeMillis();
			// new日期对象
			Date date = new Date(l);
			// 转换提日期输出格式
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			// System.out.println(dateFormat.format(date));
			return dateFormat.format(date);
		} else {
//			String time="20101125102503";  
//		    SimpleDateFormat formatter1=new SimpleDateFormat("yyyy-HH-dd HH:mm:ss");  
		    SimpleDateFormat formatter1=new SimpleDateFormat("yyyyMMddHHmmss");  
		    time = formatter1.format(formatter1.parse(time));  
//		    System.out.println(time);
			return time;
		}

	}
	/**
	* 字符串转换成日期
	* @param str
	* @return date
	*/
	public static Date StrToDate(String str) {
	  
	   SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
	   Date date = null;
	   try {
	    date = format.parse(str);
	   } catch (Exception e) {
	    e.printStackTrace();
	   }
	   return date;
	}
	/**
	* 字符串转换成日期
	* @param str
	* @return date
	*/
	public static Date str6ToDate(String str) {
	  
	   SimpleDateFormat format = new SimpleDateFormat("HHmmss");
	   Date date = null;
	   try {
	    date = format.parse(str);
	   } catch (Exception e) {
	    e.printStackTrace();
	   }
	   return date;
	}
	// 通过报文头、报文体、code、msg来组装返回 的JSON
	public static String getjsonReturn(String responseMsgHeader, String responseMsgBody, String code, String msg) {
		JsonForHardware json = new JsonForHardware();
		JsonForHardwareData jsonData = new JsonForHardwareData();
		json.setCode(code);
		json.setMsg(msg);
		jsonData.setResData(responseMsgHeader + responseMsgBody);
		json.setData(jsonData);
		String jsonString = JSON.toJSONString(json);
		return jsonString;
	}
	// 通过报文头、报文体、code、msg来组装返回 的JSON
	public static JsonCommon<String> getjsonCReturn(String responseMsgHeader, String responseMsgBody, String code, String msg) {
		JsonCommon<String> json = new JsonCommon<String>();
		json.setCode(code);
		json.setMsg(msg);
		json.setPojo(responseMsgHeader + responseMsgBody);
		return json;
	}
	// 通过报文头、报文体、code、msg来组装返回 的JSON
	public static String getjsonReturnByTime(String responseMsgHeader, String responseMsgBody, String code, String msg,
			String time) {
		JsonForHardware json = new JsonForHardware();
		JsonForHardwareData jsonData = new JsonForHardwareData();
		json.setCode("200");
		json.setMsg("ok");
		json.setTime(time);
		jsonData.setResData(responseMsgHeader + responseMsgBody);
		json.setData(jsonData);
		String jsonString = JSON.toJSONString(json);
		return jsonString;
	}
	
	//java对第三方传值过来的中文编码进行解码
	public static String decode(String str) throws UnsupportedEncodingException{
		return java.net.URLDecoder.decode(str,"UTF-8");
	}
	public static String getUrl(HttpServletRequest request){
		String url = "http://" + request.getServerName() //服务器地址  
	    + ":"   
	    + request.getServerPort()       //端口号  
	    + request.getContextPath()      //项目名称  
	    + request.getServletPath()      //请求页面或其他地址  
	    + "?" + (request.getQueryString()); //参数 
	return url;
	}
//	public static void httpGetRequest(String requestURL) {
//		// 创建默认的httpClient实例
//		CloseableHttpClient httpClient = HttpClients.createDefault();
//		try {
//			// 用get方法发送http请求
//			// HttpGet get = new HttpGet("http://www.baidu.com");
//			HttpGet get = new HttpGet(requestURL);
//			System.out.println("执行get请求:...." + get.getURI());
//			CloseableHttpResponse httpResponse = null;
//			// 发送get请求
//			try {
//				httpClient.execute(get);
//				// httpResponse = httpClient.execute(get);
//				// //response实体
//				// HttpEntity entity = httpResponse.getEntity();
//				// if (null != entity){
//				// System.out.println("响应状态码:"+ httpResponse.getStatusLine());
//				// System.out.println("-------------------------------------------------");
//				// System.out.println("响应内容:" + EntityUtils.toString(entity));
//				// System.out.println("-------------------------------------------------");
//				// }
//			} finally {
//				httpResponse.close();
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			try {
//				if (httpClient != null) {
//					httpClient.close();
//				}
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//	}

	public static void httpGetRequest(String requestURL) {
		HttpUtil.getRequest(requestURL, null);
	}
//	// 处理故障
//	public static void processError(JdbcTemplateTool jdbcTemplateTool, String codeError, String keyLink) {
//		String msg = "";
//		switch (codeError) {
//		case "01":
//			msg = "急停故障";
//			break;
//		case "02":
//			msg = "电表故障";
//			break;
//		case "03":
//			msg = "接触器故障";
//			break;
//		case "04":
//			msg = "读卡器故障";
//			break;
//		case "05":
//			msg = "内部过温故障";
//			break;
//		case "06":
//			msg = "连接器故障";
//			break;
//		case "07":
//			msg = "绝缘故障";
//			break;
//		case "08":
//			msg = "电流异常";
//			break;
//		case "09":
//			msg = "电压异常";
//			break;
//		case "0A":
//			msg = "其他故障";
//			break;
//		case "00000001":
//			msg = "其他故障";
//			break;
//		case "00000002":
//			msg = "急停故障";
//			break;
//		case "00000004":
//			msg = "电表故障";
//			break;
//		case "00000008":
//			msg = "接触器故障";
//			break;
//		case "00000010":
//			msg = "读卡器故障";
//			break;
//		case "00000020":
//			msg = "内部过温故障";
//			break;
//		case "00000040":
//			msg = "连接器故障";
//			break;
//		case "00000080":
//			msg = "绝缘故障";
//			break;
//		case "00000100":
//			msg = "输出电流异常";
//			break;
//		case "00000200":
//			msg = "输出电压异常";
//			break;
//		case "00000400":
//			msg = "充电机模块故障";
//			break;
//		case "00000800":
//			msg = "充电机通信故障";
//			break;
//		case "00001000":
//			msg = "BMS禁止充电";
//			break;
//		case "00002000":
//			msg = "输入电压异常";
//			break;
//		default:
//			msg = "其他故障";
//			break;
//		}
//		String sql_count_id = "select count(id) as countfrom char_error_record" + " where key_link='" + keyLink
//				+ "' and error_code='" + codeError + "' and state=0 and valid_flag=1";
//		int count = jdbcTemplateTool.count(sql_count_id, null);
//		if (count > 0) {
//			String sqlUpdate = "update char_error_record set update_time= now() " + "where key_link='" + keyLink
//					+ "' and error_code='" + codeError + "' and state=0  and valid_flag=1";
//			jdbcTemplateTool.getJdbcTemplate().update(sqlUpdate);
//		} else {
//			String sqlInsert = "insert into char_error_record(key_link, create_time, update_time, error_code, error_msg)"
//					+ " VALUES ('" + keyLink + "', now(), now(), '" + codeError + "', '" + msg + "')";
//			jdbcTemplateTool.getJdbcTemplate().update(sqlInsert);
//		}
//	}

	public static void sendBWtoDZ(String data) {// 发送报文到电桩中间件，socket方式主动发送报文到电桩中间件才会用到此方法

	}

	// host port 从配置文件中读取
	public static void sendSocket(String data) {// 通过socket短连接发送报文到中间件,主动发送报文到电桩中间件才会用到此方法
		//// $address = '211.149.228.101';
		// $service_port = 8090;
		try {
			Properties props = new Properties();
			InputStream in = StringUtil.class.getResourceAsStream("../config.properties");
			props.load(in);
			in.close();
			String key_host = "middleware.host";
			String host = props.getProperty(key_host);
			String key_port = "middleware.host";
			String portStr = props.getProperty(key_port);
			int port = Integer.valueOf(portStr);
			// 1.建立客户端socket连接，指定服务器位置及端口
			Socket socket = new Socket(StringUtils.isBlank(host) ? "211.149.228.101" : host, port == 0 ? 8089 : port);
			// 2.得到socket读写流
			OutputStream os = socket.getOutputStream();
			PrintWriter pw = new PrintWriter(os);
			// 输入流
			InputStream is = socket.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			// 3.利用流按照一定的操作，对socket进行读写操作
			// String info="用户名：Tom,用户密码：123456";
			pw.write(data);
			pw.flush();
			socket.shutdownOutput();
			// 接收服务器的相应
			String reply = null;
			while (!((reply = br.readLine()) == null)) {
				System.out.println("接收服务器的信息：" + reply);
			}
			// 4.关闭资源
			br.close();
			is.close();
			pw.close();
			os.close();
			socket.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static Boolean isBlank(String s) {
		if(s == null || s.length() <= 0){
			return true;
		}
		return false;
	}
	public static Boolean isNotBlank(String s) {
		if(s == null || s.length() <= 0){
			return false;
		}
		return true;
	}	
	public static Boolean isValidDate(String str) {
		  if(isBlank(str)){
			  return false;
		  }
	      boolean convertSuccess=true;
	      // 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
	       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	       try {
	      // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
	          format.setLenient(false);
	          format.parse(str);
	       } catch (ParseException e) {
	          // e.printStackTrace();
	// 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
	           convertSuccess=false;
	       } 
	       return convertSuccess;
	}
//	public static String isLogin(HttpServletRequest request) {
//		HttpSession session = request.getSession(); 
//		String oper_id = (String) session.getAttribute("oper_id"); 
//		if (StringUtil.isBlank(oper_id)) {
//			String code = "400";
//			String msg = "oper_id null";
//			String jsonStr = StringUtil.getjsonReturn("", "", code, msg);
//			return jsonStr;
//		}
//		return null;
//	}
	@SuppressWarnings("rawtypes")
	public static JsonForList isLogin(HttpServletRequest request) {
		HttpSession session = request.getSession(); 
		String login_oper_id = (String) session.getAttribute("login_oper_id"); 
		JsonForList json  = new JsonForList(); 
		if (StringUtil.isBlank(login_oper_id)) {
			json.setCode("400");
			json.setMsg("login_oper_id null,please login");
			return json;
		}
		json.setCode("200");
		json.setCode("login already");
		return json;
	}
	public static String timeDifference(Date last_connect_time){
		if(last_connect_time==null){
			return null;
		}
		Date now = new Date();
		long timeDifference = now.getTime() - last_connect_time.getTime();
		int time = (int) (timeDifference/1000) ;
		int hour = time/3600;
		int min = (time - hour*60)/60;
		int sec = time - hour*3600 - min*60;
		return String.valueOf(hour)+"时"+String.valueOf(min)+"分"+String.valueOf(sec)+"秒";
	}
	
	public static Date dateAddMin(Date time ,String min){
		Calendar ca = Calendar.getInstance(); 
		ca.setTime(time);
		ca.add(Calendar.MINUTE, Integer.valueOf(min));
		Date estimate_end_time=ca.getTime();
		return estimate_end_time;
	}
	
	public static Date dateMinusMin(Date time ,String min){
		Calendar ca = Calendar.getInstance(); 
		ca.setTime(time);
		ca.set(Calendar.MINUTE, ca.get(Calendar.MINUTE) - Integer.valueOf(min));
		return ca.getTime();
//		Date estimate_end_time=ca.getTime();
//		return estimate_end_time;
	}
	public static Long dateMinusMinLong(Date time1 ,Date time2){
		Long diff = time1.getTime() - time2.getTime();
		if(diff<=0){
			return -1L;
		}
		long nd = 1000*24*60*60;//一天的毫秒数
		long nh = 1000*60*60;//一小时的毫秒数
		long nm = 1000*60;//一分钟的毫秒数
//		long ns = 1000;//
		long min = diff%nd%nh/nm;//计算差多少分钟
		return min;
	}
	
//	/** 
//     * json格式字符串转数组 
//     */  
//    public void json2Array2(){  
//        String jsonText = "[{\"age\":16,\"id\":\"P001\",\"name\":\"TOM\"},{\"age\":21,\"id\":\"P002\",\"name\":\"JACKSON\"},{\"age\":20,\"id\":\"P003\",\"name\":\"MARTIN\"}]";  
//        JSONArray jsonArr = JSON.parseArray(jsonText);  
//        System.out.println("json2Array2()方法：jsonArr=="+jsonArr);  
//        // 输出结果：jsonArr==[{"age":16,"id":"P001","name":"TOM"},{"age":21,"id":"P002","name":"JACKSON"},{"age":20,"id":"P003","name":"MARTIN"}]  
//    }  
	
    /** 
     * json格式字符串转数组 
     */  
    public static JSONArray json2Array(String jsonText){  
        JSONArray jsonArr = JSON.parseArray(jsonText);  
        return jsonArr;
    }  
    public static boolean writefile(String path,String content){
		try{
			OutputStream out = new FileOutputStream(path);
			out.write(content.getBytes());
			out.close();
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
    }
    
    /** 
     * json格式字符串转数组 :中间件上传数据专用，eg:{\"age\":16,\"id\":\"P001\",\"name\":\"TOM\"}
     * chargerId:桩地址  ip port  source_ip source_port data  protocol_type  protocol_version  
     */  
    public static Map<String, String> ev3cString2JSONObject(String jsonText){  
//    	JSONObject myJsonObject = new JSONObject(jsonText);
//    	writefile("/tmp/temptemp.txt",jsonText);
    	JSONObject json = (JSONObject) JSON.parse(jsonText);
//		JSONObject json =StringUtil.string2JSONObject(str);
		Map<String, String> map = new HashMap<String, String>();
		map.put("chargerId",json.getString("chargerId"));
		map.put("ip",json.getString("ip"));
		map.put("port",json.getString("port"));
		map.put("source_ip",json.getString("source_ip"));
		map.put("source_port",json.getString("source_port"));
		map.put("protocol_type",json.getString("protocol_type"));
		map.put("protocol_version",json.getString("protocol_version"));
		map.put("chargerId",json.getString("chargerId"));
		//中间件使用的字段，目前是未注册时使用
		map.put("fd",json.getString("fd"));
		//以下是报文头
		map.put("data",json.getString("data"));
		String data = json.getString("data");
		map.put("codeType", data.substring(0, 2));// 启动字符68 code_type
		map.put("msgBodylength",  data.substring(2, 6));// 报文长度001E
		map.put("isRegisted", data.substring(6, 8));// 0x00:未注册 0x01:已注册
		map.put("responseCode", data.substring(8, 14));// 响应码000000
		map.put("operId", data.substring(14, 18));// 运营商0001
		map.put("communicationNo", data.substring(14, 18));// 运营商通讯编号0001
//		map.put("chargerId",  data.substring(18, 34));// 充电设备地址0755300000000015
		map.put("frameType",  data.substring(34, 36));// 帧类型A1 常常变
		map.put("serialNumber",  data.substring(36, 50));// 流水号20151123120442    	
        return map;
    }  
    
    /** 
     * json格式字符串转数组 :中间件上传数据专用，eg:{\"age\":16,\"id\":\"P001\",\"name\":\"TOM\"}
     * chargerId:桩地址  ip port  source_ip source_port data  protocol_type  protocol_version  
     */  
    public static Map<String, String> ev3c2String2JSONObject(String jsonText){  
//    	JSONObject myJsonObject = new JSONObject(jsonText);
//    	writefile("/tmp/temptemp.txt",jsonText);
    	JSONObject json = (JSONObject) JSON.parse(jsonText);
//		JSONObject json =StringUtil.string2JSONObject(str);
		Map<String, String> map = new HashMap<String, String>();
		map.put("chargerId",json.getString("chargerId"));
		map.put("ip",json.getString("ip"));
		map.put("port",json.getString("port"));
		map.put("source_ip",json.getString("source_ip"));
		map.put("source_port",json.getString("source_port"));
		map.put("protocol_type",json.getString("protocol_type"));
		map.put("protocol_version",json.getString("protocol_version"));
		map.put("chargerId",json.getString("chargerId"));
		map.put("data", json.getString("data"));
		//中间件使用的字段，目前是未注册时使用
		map.put("fd",json.getString("fd"));
        return map;
    }  
    
    
//    public static Map<String, String> string2JSONObject(String jsonText){  
//		Map<String, String> map = new HashMap<String, String>();
//		
//		String method = jsonText.substring(beginIndex, endIndex);	
//		
//		
//		map.put("chargerId",json.getString("chargerId"));
//		map.put("ip",json.getString("ip"));
//		map.put("port",json.getString("port"));
//		map.put("source_ip",json.getString("chargerId"));
//		map.put("source_port",json.getString("source_port"));
//		map.put("protocol_type",json.getString("protocol_type"));
//		map.put("protocol_version",json.getString("protocol_version"));
//		map.put("chargerId",json.getString("chargerId"));
//		//以下是报文头
//		map.put("data",json.getString("data"));
//		String data = json.getString("data");
//		map.put("codeType", data.substring(0, 2));// 启动字符68 code_type
//		map.put("msgBodylength",  data.substring(2, 6));// 报文长度001E
//		map.put("isRegisted", data.substring(6, 8));// 0x00:未注册 0x01:已注册
//		map.put("responseCode", data.substring(8, 14));// 响应码000000
//		map.put("operId", data.substring(14, 18));// 运营商0001
//		map.put("communicationNo", data.substring(14, 18));// 运营商通讯编号0001
//		map.put("chargerId",  data.substring(18, 34));// 充电设备地址0755300000000015
//		map.put("frameType",  data.substring(34, 36));// 帧类型A1 常常变
//		map.put("serialNumber",  data.substring(36, 50));// 流水号20151123120442    	
//        return map;
//    }  
	public final static String MD5(String s) {
	        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};       
	        try {
	            byte[] btInput = s.getBytes();
	            // 获得MD5摘要算法的 MessageDigest 对象
	            MessageDigest mdInst = MessageDigest.getInstance("MD5");
	            // 使用指定的字节更新摘要
	            mdInst.update(btInput);
	            // 获得密文
	            byte[] md = mdInst.digest();
	            // 把密文转换成十六进制的字符串形式
	            int j = md.length;
	            char str[] = new char[j * 2];
	            int k = 0;
	            for (int i = 0; i < j; i++) {
	                byte byte0 = md[i];
	                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
	                str[k++] = hexDigits[byte0 & 0xf];
	            }
	            return new String(str);
	        } catch (Exception e) {
	            e.printStackTrace();
	            return null;
	        }
	    }
	public static float calculateTotalPrice(String start_time, String end_time, List<OmsChargerRate> omsChargerRateList,float this_amount_before) throws ParseException{
		if(omsChargerRateList.size()==0){
			return this_amount_before;
		}
		BigDecimal this_amount_for_someDays = BigDecimal.valueOf(0.0);
		BigDecimal this_amount_for_other = BigDecimal.valueOf(0.0);
		BigDecimal this_amount_after_bigdecimal = BigDecimal.valueOf(0.0);
		float this_amount_after = 0;
//		SimpleDateFormat f_sqlTime=new SimpleDateFormat("hhmmss");
//		Time start_time_time = (Time)f_sqlTime.parse(start_time.substring(8));//只有时分秒
		Date start_time_date =StringUtil.StrToDate(start_time);
		Date end_time_date =StringUtil.StrToDate(end_time);
		long end_time_long = end_time_date.getTime();  
		long start_time_long = start_time_date.getTime();  
		long diff ;  
		if(start_time_long<end_time_long) {  
			diff = end_time_long - start_time_long;  
		} else {  
			diff = start_time_long - end_time_long;  
		} 
		long min = 0;  
		min = diff/(1000*60);

		String start_time_time = start_time.substring(8);
		long start_time_min =Long.valueOf(start_time_time.substring(0, 2))*60+ Long.valueOf(start_time_time.substring(3, 4));
////	rate1 00:00:00 到 02:00:00 rate2 02:00:01 到 23:59:59 
//	//充电时间 20160127 010000  到   20160129 040000  
		Time start_time_1 = omsChargerRateList.get(0).getStart_time();//00:00:00
		Time end_time_1 = omsChargerRateList.get(0).getEnd_time();
//		long min_1 = (end_time_1.getTime() - start_time_1.getTime())/(1000*60);
//		long min_1 = (end_time_1.getTime())/(1000*60);//此方法可能生成负数
		String end_time_1_str=new SimpleDateFormat("HHmmss").format(end_time_1);
//		System.out.println(end_time_1_str);//060000
		long min_1 = Long.valueOf(end_time_1_str.substring(0, 2))*60+ Long.valueOf(end_time_1_str.substring(3, 4));
//		System.out.println(min_1);
		BigDecimal min_1_decimal = BigDecimal.valueOf((end_time_1.getTime() - start_time_1.getTime())/(1000*60));
		BigDecimal rate_1 = omsChargerRateList.get(0).getRate();//费率为每分钟的金额
		Time start_time_2 ,start_time_3,start_time_4;
		Time end_time_2 ,end_time_3,end_time_4;
		long min_2,min_3,min_4;
		BigDecimal rate_2 ,rate_3,rate_4;
		String start_time_2_str,start_time_3_str,start_time_4_str;
		String end_time_2_str,end_time_3_str,end_time_4_str;
		switch(omsChargerRateList.size()){
		case 1:
			this_amount_after = rate_1.multiply(BigDecimal.valueOf(min)).floatValue();
			break;
		case 2:
			start_time_2 = omsChargerRateList.get(1).getStart_time();
			end_time_2 = omsChargerRateList.get(1).getEnd_time();
			start_time_2_str=new SimpleDateFormat("HHmmss").format(start_time_2);
			end_time_2_str=new SimpleDateFormat("HHmmss").format(end_time_2);
			min_2 = Long.valueOf(end_time_2_str.substring(0, 2))*60+ Long.valueOf(end_time_2_str.substring(3, 4)) - 
					Long.valueOf(start_time_2_str.substring(0, 2))*60+ Long.valueOf(start_time_2_str.substring(3, 4));
//			min_2 = (end_time_2.getTime() - start_time_2.getTime())/(1000*60);
			rate_2 = omsChargerRateList.get(1).getRate();//费率为每分钟的金额
			//240分钟  80分钟   70分钟   
			if(min>60*24){
				long days = min/(60*24);
				this_amount_for_someDays = rate_1.multiply(BigDecimal.valueOf(min_1*days)).add(rate_2.multiply(BigDecimal.valueOf(min_2*days)));
				min = min - days*60*24;
			}
			if(min>min_1){
//				this_amount_for_other = rate_1.multiply(min_1_decimal);
//				min = min - min_1;
				this_amount_for_other = this_amount_for_other.add(rate_2.multiply(BigDecimal.valueOf(min)));
//				this_amount_after_bigdecimal = this_amount_for_other.add(this_amount_for_someDays);
			}else{
				this_amount_for_other = this_amount_for_other.add(rate_2.multiply(BigDecimal.valueOf(min)));
//				this_amount_after_bigdecimal = this_amount_for_someDays.add(rate_1.multiply(BigDecimal.valueOf(min)));
			}
			break;
		case 3:
			start_time_2 = omsChargerRateList.get(1).getStart_time();
			end_time_2 = omsChargerRateList.get(1).getEnd_time();
			start_time_2_str=new SimpleDateFormat("HHmmss").format(start_time_2);
			end_time_2_str=new SimpleDateFormat("HHmmss").format(end_time_2);
			min_2 = Long.valueOf(end_time_2_str.substring(0, 2))*60+ Long.valueOf(end_time_2_str.substring(3, 4)) - 
					Long.valueOf(start_time_2_str.substring(0, 2))*60+ Long.valueOf(start_time_2_str.substring(3, 4));
//			min_2 = (end_time_2.getTime() - start_time_2.getTime())/(1000*60);
			rate_2 = omsChargerRateList.get(1).getRate();//费率为每分钟的金额
			start_time_3 = omsChargerRateList.get(2).getStart_time();
			end_time_3 = omsChargerRateList.get(2).getEnd_time();
//			min_3 = (end_time_3.getTime() - start_time_3.getTime())/(1000*60);
			start_time_3_str=new SimpleDateFormat("HHmmss").format(start_time_3);
			end_time_3_str=new SimpleDateFormat("HHmmss").format(end_time_3);
			min_3 = Long.valueOf(end_time_3_str.substring(0, 2))*60  +
					Long.valueOf(end_time_3_str.substring(3, 4)) - 
					Long.valueOf(start_time_3_str.substring(0, 2))*60 - 
					Long.valueOf(start_time_3_str.substring(3, 4));
			rate_3 = omsChargerRateList.get(2).getRate();//费率为每分钟的金额
			if(min>60*24){
				long days = min/(60*24);
				this_amount_for_someDays = rate_1.multiply(BigDecimal.valueOf(min_1*days)).add(rate_2.multiply(BigDecimal.valueOf(min_2*days)))
						.add(rate_3.multiply(BigDecimal.valueOf(min_3*days)));
				min = min - days*60*24;
			}
			if(start_time_min<=min_1){
				if(min<=min_1){
					this_amount_for_other = this_amount_for_other.add(rate_1.multiply(BigDecimal.valueOf(min)));
				}else{
					min = min - min_1;
					if(min<min_2){
						this_amount_for_other = this_amount_for_other.add(rate_2.multiply(BigDecimal.valueOf(min)));
					}else{
						this_amount_for_other = this_amount_for_other.add(rate_2.multiply(BigDecimal.valueOf(min_2)));
						min = min - min_2;
						this_amount_for_other = this_amount_for_other.add(rate_3.multiply(BigDecimal.valueOf(min_3- min)));
					}
				}
			}
			if((start_time_min>min_1)&&(start_time_min<=min_2)){
				if(min<=min_2){
					this_amount_for_other = this_amount_for_other.add(rate_2.multiply(BigDecimal.valueOf(min)));
				}else{
					min = min - min_2;
					if(min<min_3){
						this_amount_for_other = this_amount_for_other.add(rate_3.multiply(BigDecimal.valueOf(min)));
					}else{
						this_amount_for_other = this_amount_for_other.add(rate_3.multiply(BigDecimal.valueOf(min_3)));
						min = min - min_3;
						this_amount_for_other = this_amount_for_other.add(rate_1.multiply(BigDecimal.valueOf(min_1- min)));
					}
				}
			}	
			if((start_time_min>min_2)&&(start_time_min<=min_3)){
				if(min<=min_3){
					this_amount_for_other = this_amount_for_other.add(rate_3.multiply(BigDecimal.valueOf(min)));
				}else{
					min = min - min_3;
					if(min<min_1){
						this_amount_for_other = this_amount_for_other.add(rate_1.multiply(BigDecimal.valueOf(min)));
					}else{
						this_amount_for_other = this_amount_for_other.add(rate_1.multiply(BigDecimal.valueOf(min_1)));
						min = min - min_1;
						this_amount_for_other = this_amount_for_other.add(rate_2.multiply(BigDecimal.valueOf(min_2- min)));
					}
				}
			}	
			break;
		case 4:
			start_time_2 = omsChargerRateList.get(1).getStart_time();
			end_time_2 = omsChargerRateList.get(1).getEnd_time();
//			min_2 = (end_time_2.getTime() - start_time_2.getTime())/(1000*60);
			start_time_2_str=new SimpleDateFormat("HHmmss").format(start_time_2);
			end_time_2_str=new SimpleDateFormat("HHmmss").format(end_time_2);
			min_2 = Long.valueOf(end_time_2_str.substring(0, 2))*60+ Long.valueOf(end_time_2_str.substring(3, 4)) - 
					Long.valueOf(start_time_2_str.substring(0, 2))*60+ Long.valueOf(start_time_2_str.substring(3, 4));
			rate_2 = omsChargerRateList.get(1).getRate();//费率为每分钟的金额
			start_time_3 = omsChargerRateList.get(2).getStart_time();
			end_time_3 = omsChargerRateList.get(2).getEnd_time();
//			min_3 = (end_time_3.getTime() - start_time_3.getTime())/(1000*60);
			start_time_3_str=new SimpleDateFormat("HHmmss").format(start_time_3);
			end_time_3_str=new SimpleDateFormat("HHmmss").format(end_time_3);
			min_3 = Long.valueOf(end_time_3_str.substring(0, 2))*60 +
					Long.valueOf(end_time_3_str.substring(3, 4)) - 
					Long.valueOf(start_time_3_str.substring(0, 2))*60 -
					Long.valueOf(start_time_3_str.substring(3, 4));
			rate_3 = omsChargerRateList.get(2).getRate();//费率为每分钟的金额
			start_time_4 = omsChargerRateList.get(3).getStart_time();
			end_time_4 = omsChargerRateList.get(3).getEnd_time();
			start_time_4_str=new SimpleDateFormat("HHmmss").format(start_time_4);
			end_time_4_str=new SimpleDateFormat("HHmmss").format(end_time_4);
			min_4 = Long.valueOf(end_time_4_str.substring(0, 2))*60 + 
					Long.valueOf(end_time_4_str.substring(3, 4)) - 
					Long.valueOf(start_time_4_str.substring(0, 2))*60 - 
					Long.valueOf(start_time_4_str.substring(3, 4));
//			min_4 = (end_time_4.getTime() - start_time_4.getTime())/(1000*60);
			rate_4 = omsChargerRateList.get(3).getRate();//费率为每分钟的金额
			if(min>60*24){
				long days = min/(60*24);
				this_amount_for_someDays = rate_1.multiply(BigDecimal.valueOf(min_1*days)).add(rate_2.multiply(BigDecimal.valueOf(min_2*days)))
						.add(rate_3.multiply(BigDecimal.valueOf(min_3*days))).add(rate_4.multiply(BigDecimal.valueOf(min_4*days)));
				min = min - days*60*24;
			}
			if(start_time_min<=min_1){
				if(min<=min_1){
					this_amount_for_other = this_amount_for_other.add(rate_1.multiply(BigDecimal.valueOf(min)));
				}else{
					min = min - min_1;
					if(min<min_2){
						this_amount_for_other = this_amount_for_other.add(rate_2.multiply(BigDecimal.valueOf(min)));
					}else{
						this_amount_for_other = this_amount_for_other.add(rate_2.multiply(BigDecimal.valueOf(min_2)));
						min = min - min_2;
						if(min<min_3){
							this_amount_for_other = this_amount_for_other.add(rate_3.multiply(BigDecimal.valueOf(min)));
						}else{
							min = min - min_3;
							this_amount_for_other = this_amount_for_other.add(rate_4.multiply(BigDecimal.valueOf(min_4- min)));
						}
					}
				}
			}
			if(start_time_min<=min_2){
				if(min<=min_2){
					this_amount_for_other = this_amount_for_other.add(rate_2.multiply(BigDecimal.valueOf(min)));
				}else{
					min = min - min_2;
					if(min<min_3){
						this_amount_for_other = this_amount_for_other.add(rate_3.multiply(BigDecimal.valueOf(min)));
					}else{
						this_amount_for_other = this_amount_for_other.add(rate_3.multiply(BigDecimal.valueOf(min_3)));
						min = min - min_3;
						if(min<min_4){
							this_amount_for_other = this_amount_for_other.add(rate_4.multiply(BigDecimal.valueOf(min)));
						}else{
							min = min - min_4;
							this_amount_for_other = this_amount_for_other.add(rate_1.multiply(BigDecimal.valueOf(min_1- min)));
						}
					}
				}
			}
			if(start_time_min<=min_3){
				if(min<=min_3){
					this_amount_for_other = this_amount_for_other.add(rate_3.multiply(BigDecimal.valueOf(min)));
				}else{
					min = min - min_3;
					if(min<min_4){
						this_amount_for_other = this_amount_for_other.add(rate_4.multiply(BigDecimal.valueOf(min)));
					}else{
						this_amount_for_other = this_amount_for_other.add(rate_4.multiply(BigDecimal.valueOf(min_4)));
						min = min - min_4;
						if(min<min_1){
							this_amount_for_other = this_amount_for_other.add(rate_1.multiply(BigDecimal.valueOf(min)));
						}else{
							min = min - min_1;
							this_amount_for_other = this_amount_for_other.add(rate_2.multiply(BigDecimal.valueOf(min_2- min)));
						}
					}
				}
			}
			if(start_time_min<=min_4){
				if(min<=min_4){
					this_amount_for_other = this_amount_for_other.add(rate_4.multiply(BigDecimal.valueOf(min)));
				}else{
					min = min - min_4;
					if(min<min_1){
						this_amount_for_other = this_amount_for_other.add(rate_1.multiply(BigDecimal.valueOf(min)));
					}else{
						this_amount_for_other = this_amount_for_other.add(rate_1.multiply(BigDecimal.valueOf(min_1)));
						min = min - min_1;
						if(min<min_2){
							this_amount_for_other = this_amount_for_other.add(rate_2.multiply(BigDecimal.valueOf(min)));
						}else{
							min = min - min_2;
							this_amount_for_other = this_amount_for_other.add(rate_3.multiply(BigDecimal.valueOf(min_3- min)));
						}
					}
				}
			}
			break;
		default:
			break;
		}
		this_amount_after_bigdecimal = this_amount_for_someDays.add(this_amount_for_other);
		this_amount_after = this_amount_after_bigdecimal.floatValue();
		return this_amount_after;
	}	
	
	public static int time30(String time){
		int temp1_1 = Integer.valueOf(time.substring(0,2))*2;
		int temp1_2 = Integer.valueOf(time.substring(2,4))/30;
		return (temp1_1 + temp1_2);
	}
	//三个时间点换成48个时间段,时间格式：1530 为下午3点30分
	public static String ThreetimeTo48(String time1,String time2 ,String time3){
		if(isBlank(time1)||isBlank(time2)||isBlank(time3)){
			return null;
		}
		int time1_int = time30(time1);
		int time2_int = time30(time2);
		int time3_int = time30(time3);
		StringBuilder sb =new StringBuilder();
		for(int i=0;i<time1_int;i++){
			sb.append("01");
		}
		for(int i=0;i<time2_int-time1_int;i++){
			sb.append("02");
		}
		for(int i=0;i<time3_int-time2_int;i++){
			sb.append("03");
		}
		for(int i=0;i<48-time3_int;i++){
			sb.append("04");
		}
		return sb.toString();
	}
	
	//三个时间点换成48个时间段,时间格式：1530 为下午3点30分
	public static String[] fortyeight2Threetime(String fortyeightTime_bin){
		if(isBlank(fortyeightTime_bin)){
			return null;
		}
		int time1 = 0,time2 = 0,time3 = 0,time4 = 0;
		for(int i=0;i<fortyeightTime_bin.length();i++){
			switch(fortyeightTime_bin.substring(i, i+1)){
			case "0":
				break;
			case "1":
				time1++;
				break;
			case "2":
				time2++;
				break;
			case "3":
				time3++;
				break;
			case "4":
				time4++;
				break;
			default:
				break;
			}
		}
		String[] array = new  String[6];
		String time1_str = null,time2_str = null,time3_str = null,time4_str = null;
		if(time1%2==0){
			time1_str = time1/2+"时";
		}else{
			time1_str = time1/2+"时30分";
		}
		if((time2+time1)%2==0){
			time2_str = (time2+time1)/2+"时";
		}else{
			time2_str = (time2+time1)/2+"时30分";
		}
		if((time3+time2+time1)%2==0){
			time3_str = (time3+time2+time1)/2+"时";
		}else{
			time3_str = (time3+time2+time1)/2+"时30分";
		}
		array[0] = time1_str;
		array[1] = time2_str;
		array[2] = time3_str;
		array[3] = String.valueOf(time1);
		array[4] = String.valueOf(time2);
		array[5] = String.valueOf(time3);
		return array; 
	}	
	
	
	public static String ev3cMsgBody16Length(String ev3c_msgBody){
		if(isBlank(ev3c_msgBody)){
			return "0000";
		}
		String value = Integer.toHexString(ev3c_msgBody.length()/2);
		switch(value.length()){
		case 1:
			return "0"+value+"00";
		case 2:
			return value+"00";
		case 3:
			return value.substring(1,3)+"0"+value.substring(0,1);
		case 4:
			return value;
		default:
			return "0000";	
		}
	}
//	假设有Person这个类，有json类型数据str=str = [{"name":"张三","age":"1"},{"name":"李四","age":"4"}]，那么
//	List listt = json.parseArray(str, Person.class);listt就可以接收str了，
	public static List<String> request2List(HttpServletRequest request,String str){
		if(request==null||isBlank(str)){
			return null;
		}
		String str1 = request.getParameter(str);
		List<String> list =  JSON.parseArray(str1,String.class);
		return list;
	}
	
	public static String[] request2Array(HttpServletRequest request,String str){
		if(request==null||isBlank(str)){
			return null;
		}
		String str1 = request.getParameter(str);
		List<String> list =  JSON.parseArray(str1, String.class);
		String[] array = (String[]) list.toArray(new String[0]);
		return array;
	}
	
	
	
	
//	public static Map<String,String> removeNullValue(Map<String,String> map){
//		 Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();  
//		 while(it.hasNext()){  
//	            Map.Entry<String, String> entry=it.next();  
//	            String key=entry.getKey();  
//	            if(map.get(key)==null){  
////	                System.out.println("delete this: "+key+" = "+key);  
//	                //map.put(key, "奇数");   //ConcurrentModificationException  
//	                //map.remove(key);      //ConcurrentModificationException  
//	                it.remove();        //OK   
//	            }  
//	        }  
//		 return map;
//	}
	public static void removeNullValue(Map<String,String> map){
		 Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();  
		 while(it.hasNext()){  
	            Map.Entry<String, String> entry=it.next();  
	            String key=entry.getKey();  
	            if(map.get(key)==null){  
//	                System.out.println("delete this: "+key+" = "+key);  
	                //map.put(key, "奇数");   //ConcurrentModificationException  
	                //map.remove(key);      //ConcurrentModificationException  
	                it.remove();        //OK   
	            }  
	        }  
	}
	
	// public static String getProtocalVersion(String
	// keyLink){//根据充电桩设备地址来获取协议版本号
	// String sql = "select ev_protocol_version from ev_char where key_link
	// ='"+keyLink+"' order by id desc limit 0, 1";
	// List<Map<String,Object>> keyLinkOldList =
	// jdbcTemplateTool.getJdbcTemplate().queryForList(sqlKeyLinkQuery);
	// Map<String,Object> map = keyLinkOldList.get(0);
	// String tempkeylink = map.get("key_link").toString();
	// }
//	public static void main(String[] args) {
		// String data
		// ="68001E0100000000010755300000000015A120151123120442000050242196850201000000000000000000000000000000000001020102";
		//// System.out.println(data.length());//0102
		// String fac_login_name = data.substring(50, 58); //注册账号 00005024
		// String fac_password = data.substring(58, 66); //注册密码 21968502
		// String ev_fac_type1 = data.substring(66, 68); //设备一级类型 01
		// String ev_fac_type2 = data.substring(68, 70); //设备二级类型 00
		// String ev_sn = data.substring(70, 86); //设备SN 16位
		// String ev_gps = data.substring(86, 102); //GPS坐标 16位 00..00
		// String ev_soft_version1 = data.substring(102, 106); //版本号 0102
		// String ev_protocol_version = data.substring(106, 110);//版本号 0102
		// System.out.println(fac_login_name);
		// System.out.println(fac_password);
		// System.out.println(ev_fac_type1);
		// System.out.println(ev_fac_type2);
		// System.out.println(ev_sn);
		// System.out.println(ev_gps);
		// System.out.println(ev_soft_version1);
		// System.out.println(ev_protocol_version);
		// String key_link = "0755300000000015";
		// System.out.println(getSKeyLink(key_link));
		// String key_link = "00000000010";
		// System.out.println(getNextCode(key_link));
		// String key1 = "0755300000000017";
		// System.out.println(key1.substring(5));
		// System.out.println(getNextCode(key1.substring(5)));
		// String key_link = "8090";
		// System.out.println(str2HexStr(key_link));
//		 String ip = "211.149.236.61";//d395ec3d
//		 System.out.println(ip2HexStr(ip));
		// System.out.println(complement("1E",4));
		// System.out.println("000050242196850201000000000000000000000000000000000001020102".length());
		// String data =
		// "68002B010000000001075530000000001551201511201130560001000000000000000000000000579E00000000000000000001FFFFFF0000000000000000000000000000";
		// data.substring(53, 54);
		// System.out.println(data.substring(54, 62));
//		 System.out.println(String.valueOf(int16to10ByParam("579E", 100)));
//		 System.out.println(String.valueOf(int16to10ByParam("10", 1)));
		 
//		 System.out.println(float10to16ByParamDesc("8090", 1, 4));
		// System.out.println(String.valueOf(float16to10ByParam("579E",100)));
		// System.out.println(String.valueOf(float16to10ByParam("579",100)));
//		 System.out.println(str2HexStr("1010"));
//		 System.out.println(Integer.toHexString(1000));
//		 System.out.println(float16to10ByParam("100e0000",100));
		 
//		 System.out.println(float16to10ByParamDesc("260e0000",100));
//		 System.out.println(float16to10ByParamDesc("260e",100));
//		 System.out.println(float10to16ByParamDesc("36.22",100,4));
//		 System.out.println(float10to16ByParamDesc("16",1,2));
//		 System.out.println(complement(float10to16ByParamDesc("16",1,2),4));
		 
//		 System.out.println( float10to16ByParamDesc("360",1,4));
//		String asd ="abcdefgh";
//		String[] ss =asd.split("", 4);
//		for(String s :ss){
//			System.out.println(s);
//		}
//		 System.out.println(36.23/100);
//		System.out.println(now14time());
//		System.out.println(sixteen2tenInt("1E"));
		// String text = "Example on how to convert a String to an InputStream";
		//
		// try {
		// InputStream is = new ByteArrayInputStream(text.getBytes());
		//
		// int byteRead;
		// while ((byteRead = is.read()) != -1) {
		// System.out.print((char)byteRead);
		// }
		// System.out.println();
		// is.close();
		// } catch (UnsupportedEncodingException e) {
		// e.printStackTrace();
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		//
//		String a = "0100";
//		int d = Integer.parseInt(a, 2); // 2进制
//		int o = Integer.parseInt(a, 8); // 8进制
//		System.out.println(d);
//		System.out.println(o);
//		System.out.println(StringUtil.float10to16ByParamDesc("150", 1, 4));
//		System.out.println(now12time());
//		StringBuilder sb = new StringBuilder("qwf,");
//		System.out.println(sb.deleteCharAt(sb.length()-1));
//		Date we = new Date(System.currentTimeMillis() - 30 * 60 * 1000 -222);
//		System.out.println(timeDifference(we));
		
//		 System.out.println(MD5("123"));
//	        System.out.println(MD5("加密"));
//		System.out.println("12345678901234567890".substring(10, 20));
	    /** 
	     * json格式字符串转数组 :中间件上传数据专用，eg:{\"age\":16,\"id\":\"P001\",\"name\":\"TOM\"}
	     */  
//		String as  = "{\"age\":16,\"id\":\"P001\",\"name\":\"TOM\"}";
//		JSONObject json  =	string2JSONObject(as);
//		System.out.println(json.get("age"));
//		System.out.println(ip2HexStr("211.149.228.101"));
//		System.out.println(StringUtil.float10to16ByParamDesc("8090", 1, 4));
//		System.out.println(StringUtil.float10to16ByParamDesc("2", 1, 2));
//		System.out.println(StringUtil.float10to16ByParamDesc("12", 1, 2));
//		System.out.println(StringUtil.float10to16ByParamDesc("223.01", 100, 6));
//		System.out.println(StringUtil.int16to10ByParam("1D5700", 100));
//		System.out.println(float16to10ByParamDesc("1D5700", 100));
//		int i = 0;
//		System.out.println(i*30+"_"+(i+1)*30);
//		i = 1;
//		System.out.println(i*30+"_"+(i+1)*30);
//		String as = "0101010202020303030304040404040404";
//		int timeRate1 = as.lastIndexOf("01");
//		System.out.println(timeRate1);
//		int  timeRate1_min = (timeRate1 + 2 )/2  * 30 ;
//		System.out.println(timeRate1_min);
//		int  timeRate1_hour = (timeRate1_min)/60 ;
//		String timeRate1_end_time ="";
//		if(timeRate1_min%60!=0){
//			String timeRate1_hour_str =String.valueOf(timeRate1_hour+0.5);
//			System.out.println(timeRate1_hour_str);
//			timeRate1_end_time = timeRate1_hour+":30:00";
//		}else{
//			timeRate1_end_time = timeRate1_hour+":00:00";
//		}
//		System.out.println(timeRate1_end_time);
//		
//		int timeRate2 = as.lastIndexOf("02");
//		int  timeRate2_min = (timeRate2 + 2 )/2  * 30 ;
//		System.out.println(timeRate2_min);
//		int  timeRate2_hour = (timeRate2_min)/60 ;
//		String timeRate2_end_time ="";
//		if(timeRate2_min%60!=0){
//			String timeRate2_hour_str =String.valueOf(timeRate2_hour+0.5);
//			System.out.println(timeRate2_hour_str);
//			timeRate2_end_time = timeRate2_hour+":30:00";
//		}else{
//			timeRate2_end_time = timeRate2_hour+":00:00";
//		}
//		System.out.println(timeRate2_end_time);
		
		
//		String timeRate1_start_time = "00:00:00";
////		String timeRate1_end_time = "00"+":"+"00"+":00";
//		System.out.println(timeRate1_hour);
//		int timeRate2 = as.lastIndexOf("02");
//		System.out.println(timeRate2);
//		int  timeRate2_min = (timeRate2 + 2 )/2  * 30 ;
//		System.out.println(timeRate2_min);
//		int asdfa  = (timeRate2 + 2 )%4 ;
//		int  timeRate2_hour = (timeRate2 + 2 )/4  +(timeRate2 + 2 )%4;
//		System.out.println(timeRate2_hour);
		
		
//		Date starttime = StringUtil.str6ToDate("000000");    //开始时间
//		Date endtime =StringUtil.str6ToDate("010000");    //结束时间
//		long seconds = endtime.getTime() - starttime.getTime();
//		System.out.println(seconds/(60*30*1000));
		
//		System.out.println(float10to16ByParamDesc(String.valueOf(11), 1, 2));
		
		
//		String kk = "method=chargerLogin&protocol_type=1&protocol_version=0101&chargerId=00010028300000000025&ip=192.168.5.208&port=8090&source_ip=192.168.5.6&source_port=10952&data=68001C0100000000010028300000000025A12015112610101400005015935590750102201505190000000800000000000000000300";
//		String kk ="{\"method\":\"chargerLogin\",\"protocol_type\":\"1\",\"protocol_version\":\"0101\",\"chargerId\":\"00010028300000000025\"}";
//		String kk ="{\"method\":\"chargerLogin\",\"protocol_type\":\"1\",\"protocol_version\":\"0101\",\"chargerId\":\"00010028300000000025\",\"ip\":\"192.168.5.208\",\"port\":\"8090\",\"source_ip\":\"192.168.5.6\",\"source_port\":\"10952\",\"data\":\"68001C0100000000010028300000000025A12015112610101400005015935590750102201505190000000800000000000000000300\"}";

//		Map<String, String>  map = string2JSONObject(kk);
//		String kk = "method=chargerLogin&protocol_type=1";
//		Object  asd = JSON.parse(kk);
//		JSONObject json = (JSONObject) JSON.parse(kk);
//		System.out.println(json);
		
//		System.out.println("11");
//		System.out.println(ev3cMsgBodyBin("008613553523147809553100"));
//		String data = "682D00010000000001002830000000002572201512131234561D5700800C0010000010000000BC1B";
//		int this_minute = (int)StringUtil.float16to10ByParamDesc(data.substring(68, 74), 1);//充电时间
		//*输出功率(W)	BIN码	3	系数为1	低字节在前，高字节在后，如 0x00 0xBC 0x1B,表示实际数据为 7100 W
//		int this_power = (int)StringUtil.float16to10ByParamDesc(data.substring(74, 80), 1);//	
		
		
//		System.out.println(ev3cMsgBody16Length("01234567890123456789"));

//		float   f   =  123123.123111111f;
//		 float   f1 =  f/100;
//		 BigDecimal   b  =   new BigDecimal(f1);
//		 float   f2   =  b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
//		 float num=(float)(Math.round(f2*100)/100);
//		System.out.println(num);
//
//	}

	public static float convertBinToInt(String bin, int scale)
	{
		StringBuilder sb = new StringBuilder("");
		for (int i = 0; i < bin.length(); i = i + 2)
		{
			sb.append(bin.substring(bin.length() - i - 2, bin.length() - i));
		}
		//		String k_str  = str.substring(6, 8)+str.substring(4, 6)+str.substring(2, 4)+str.substring(0, 2);
		long k_int = Long.parseLong(sb.toString(), 16);

		//		 float   f   =  34.232323;
		//		 BigDecimal   b  =   new BigDecimal(f);
		//		 float   f1   =  b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
		float f = k_int;
		float f1 = f / scale;
		BigDecimal b = new BigDecimal(f1);
		float f2 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
		return f2;
	}

	public static float convertBinToIntWithNegative(String bin, int scale)
	{
		if(scale == 0 )
			return 0;
		StringBuilder sb = new StringBuilder("");
		for (int i = 0; i < bin.length(); i = i + 2)
			sb.append(bin.substring(bin.length() - i - 2, bin.length() - i));
		String origin = sb.toString();
		String first = origin.substring(0, 1);
		int int_first = Integer.parseInt(first, 16);

		String target = origin;
		if (int_first >= 8)
		{
			target = "-" + Integer.toString(int_first - 8, 16) + origin.substring(1);
		}
		long k_int = Long.parseLong(target, 16);
		BigDecimal t = new BigDecimal((float) k_int / scale);
		return t.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
	}

	public static float convertBinToIntByBit(String bin, int scale, int pos_start, int post_end)
	{
		if(scale == 0)
			return 0;
		if (bin.length() * 4 < post_end)
			throw new IllegalArgumentException("post_end should not be larger than bin length * 4");
		if (pos_start < 0 || pos_start > post_end)
			throw new IllegalArgumentException("post_start is invalid ");
		StringBuilder sb = new StringBuilder("");
		for (int i = 0; i < bin.length(); i = i + 2)
			sb.append(bin.substring(bin.length() - i - 2, bin.length() - i));
		String origin = sb.toString();

		long k_int = Long.parseLong(origin, 16);
		String binary = Long.toString(k_int, 2);
//		System.out.println(binary);

		int end = binary.length() + 1 - pos_start;
		int start = binary.length() - post_end;
		if(start < 0)
			start = 0;
		String target = binary.substring(start, end);
//		System.out.println(Integer.valueOf(target, 2));
		int value = Integer.valueOf(target, 2);
		return ((float)value)/scale;
	}

	/**
	 * ip地址转16进制,去掉.不够时左补0
	 * @param ip
	 * @return length 补足长度
	 */
	public static String ip2HexStrLeftComplement(String ip, int length) {
		String[] ips = ip.split("\\.");
		StringBuilder sb = new StringBuilder("");
		for (String tempip : ips) {
			// Integer.toHexString(Integer.valueOf(tempip));
			String relult = String.valueOf(Integer.toHexString(Integer.valueOf(tempip)));
			if (relult.length() < length) {
				sb.append("0").append(relult); // 左补一个0
			} else {
				sb.append(relult);
			}
		}
		return sb.toString();
	}

	
	


	
	public static long int16to10ByParamDesc(String bin)
	{
		StringBuilder sb = new StringBuilder("");
		for (int i = 0; i < bin.length(); i = i + 2)
			sb.append(bin.substring(bin.length() - i - 2, bin.length() - i));
		String origin = sb.toString();
		return Long.parseLong(sb.toString(), 16);
	}

	/**
	 * 发送报文给中间件时,传递的文本长度为字节长度
	 * @param ev3c_msgBody
	 * @return
	 */
	public static String ev3cMsgBodyBinDivided(String ev3c_msgBody){
		String  length16 = Integer.toHexString(ev3c_msgBody.length()/2);
		if(length16.length()==1){
			length16 = "0"+length16+"00";
		}else if(length16.length()==2){
			length16 =  length16+"00";
		}

		return length16;
	}
	
	/**
	 * 根据指定长度截取并反转字符串(例如:02 01 2b 5c 返回结果:5c 2b 01 02)
	 * @param codeStr
	 * @param length 指定长度
	 * @return 反转失败返回:n个0(n:字符串codeStr长度)
	 */
	public static String reverseStr(String codeStr, int length) {
		// 处理:默认返回失败
		String result = ""; // 默认返回失败
		int index = 0;
		while(index < codeStr.length()){
			result = result.concat("0");
			index ++;
		}
		if (codeStr.length() % length == 0) { // 处理字符串反转
			StringBuilder sb = new StringBuilder("");
			for (int i = 0; i < codeStr.length() / length; i++) {
				sb.append(codeStr.substring(index - length, index));
				index = index - length;
			}
			result = sb.toString();
		}
		return result;
	}
	
	/**
     * 验证对象是否为空
     * @author peizhide
     * @creaetime 2014-11-28 下午2:15:18
     * @param obj 对象
     * @return true:为空 false:非空
     */
    public static boolean objectIsNull(Object obj) {
        return (null == obj) ? true : false;
    }
    
    /**
     * 判断集合是否为空
     * @author peizhide
     * @createtime 2016-05-11 下午8:22:25
     * @param collection 需要验证的集合
     * @return true:为空  false：不为空
     */
    public static boolean isEmpty(Collection<?> collection) {
        return isNull(collection) ? true : collection.size() <= 0;
    }
    
    /**
     * 判断入库对象是否为空
     * @author peizhide
     * @createtime 2016-05-11 下午8:21:37
     * @param obj 传入参数对象
     * @return 对象是否为空结果
     */
    public static boolean isNull(Object obj) {
        return NULL_OBJECT == obj;
    }
    
    /**
     * 判断该值为正数
     * @author peizhide
     * @createtime 2016-05-11 下午8:11:54
     * @param str 整数
     * @return 返回true:正数 false:非正数
     */
    public static boolean isPositiveNumber(String str) {
        if (isEmpty(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[1-9]*[1-9][0-9]*$");
        return pattern.matcher(str).matches();
    }
    
    /**
     * 判断字符串是否为空
     * @author peizhide
     * @createtime 2016-05-11 下午8:22:20
     * @param str 需要验证的字符串
     * @return true:为空  false:不为空
     */
    public static boolean isEmpty(String str) {
        return isNull(str) ? true : str.trim().length() <= 0;
    }
    
    /**
     * 判断字符串是否超出长度
     * @author peizhide
     * @createtime 2016-05-11 下午8:24:07
     * @param field 字段
     * @param maxLength 指定长度
     * @return 操作结果
     */
    public static boolean isOutOfMaxLength(String field, int maxLength) {
        return isNull(field) ? false : field.length() > maxLength;
    }
    
	public String getValueByCopyright(String key) {
		//CopyrightUtil  copyrightUtil =new CopyrightUtil();
		
		//return copyrightUtil.getCopyright();
		String filePath = "WEB-INF\\classes\\copyRight.properties";   
		//获取servlet的上下文    
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext(); 
		ServletContext context = webApplicationContext.getServletContext();   
		String webRootPath = context.getRealPath("\\");   
		//最后得到文件的绝对路径    
		String path = webRootPath+filePath ;    
	
		String classPath = this.getClass().getClassLoader().getResource("/").getPath();
	    String rootPath  = "";
	    //windows下
	    if("\\".equals(File.separator)){   
	        rootPath  = classPath.substring(1,classPath.indexOf("/WEB-INF/classes"));
	        rootPath = rootPath.replace("/", "\\");
	        path = rootPath+"\\WEB-INF\\classes\\copyRight.properties"  ;
	    }
	    //linux下
	    if("/".equals(File.separator)){   
	        rootPath  = classPath.substring(0,classPath.indexOf("/WEB-INF/classes"));
	        rootPath = rootPath.replace("\\", "/");
	        path = rootPath+"/WEB-INF/classes/copyRight.properties" ;;
	    }
        String value="";
        Properties prop =  new  Properties();  
        try  {
        //Reader in = new InputStreamReader(new FileInputStream("D:\\workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\dz_OMS_V2.1\\WEB-INF\\classes\\copyRight.properties"), "UTF-8");
        	Reader in = new InputStreamReader(new FileInputStream(path), "UTF-8");
            prop.load(in);  
            value = prop.getProperty( "key" ).trim();  
        }  catch  (IOException e) {  
            e.printStackTrace();  
        } 
		return value;
	}
	public static List<String> request2List222(String str){
		String str1 = str;
		List<String> list =  JSON.parseArray(str1,String.class);
		return list;
	}
	
	//取得当前用户对应的用户类型
		public static OmsOperList getUserByRequest(HttpServletRequest request){
			HttpSession new_session = request.getSession();
			String entity_id = null;
			if(new_session!=null){
				OmsOperList oper = (OmsOperList) new_session.getAttribute(BaseAction.CommonParam.SESSION_USER);
				return oper;
			}
			return null;
		}	
	//取得当前用户对应的运营商ID
	public static String getUserEntityId(HttpServletRequest request){
		HttpSession new_session = request.getSession();
		String entity_id = null;
		if(new_session!=null){
			OmsOperList oper = (OmsOperList) new_session.getAttribute(BaseAction.CommonParam.SESSION_USER);
			if(oper.getEntity_id()!=null ){
				entity_id = oper.getEntity_id();
					return entity_id;
			}	
		}
		return null;
	}	
	//当前用户是否是超级运营商下属的管理员
	public static Boolean isSuperMerchant(HttpServletRequest request){
		HttpSession new_session = request.getSession();
		String entity_id = null;
		if(new_session!=null){
			OmsOperList oper = (OmsOperList) new_session.getAttribute(BaseAction.CommonParam.SESSION_USER);
			if(oper.getEntity_id()!=null ){
				entity_id = oper.getEntity_id();
				OmsOperationSpList omsOperationSpList = su.omsOperationSpListDao.findOneExampleByCondition(new OmsOperationSpList(), " where oper_merchant_id = '"+entity_id+"'");
//				new OmsCharger(), "where charger_id like '"+cityCode+"%' ORDER by charger_id DESC LIMIT 0,1");
				if(omsOperationSpList.getSuper_flag()!=null && omsOperationSpList.getSuper_flag() == 1){
					return true;
				}
			}	
		}
		return false;
	}
	
	
	
	public static void main(String[] args)
	{
//		System.out.println(ip2HexStr("117.136.70.109"));
//		String rate2_bin = StringUtil.float10to16ByParamDesc("2.1", 100, 4);
//		System.err.println(rate2_bin);
		
//		String sss = "12345678901234567890,2345678901234567891";
//		String[] ddd = sss.split(",");
//		System.out.println(ddd[0]);
		System.out.println(StrToDate("20000000000000"));
//		System.out.println(request2List222("12345678901234567890,2345678901234567891"));
		
	}
	
}
